# -*- coding: utf-8 -*-
from scpy.logger import get_logger
import os
import sys
from SCAWS import *

logger = get_logger(__file__)
APP_NAME = 'sc-recruitment'
TAR_FILE_NAME = 'sc-crawler-worker-recruitment.tar.gz'
S3_CODE_BASE_URL = 's3://sc-resource/crawler/{app_name}/'
INSTANCE_NUM = 1
INSTANCE_NAME = 'sc-crawler-recruitment'
IMAGE_ID = 'ami-8b1ecae6'
PROCESS_NUM = 5
initial_codes = """#!/bin/sh
set -e
aws s3 sync {s3_url} /usr/app/
cd /usr/app/
rm -rf sc-crawler-base
tar xvf *.tar.gz
rm -rf *.tar.gz
cd /usr/app/{app_name}/
pip install -r requirements.txt
for k in $(seq 1 {process_num} )
 do
    sudo nohup python worker.py recruitment_task -e test 1>/dev/null 2>/dev/null &
    sudo nohup python worker.py recruitment_downnload_lagou -e test 1>/dev/null 2>/dev/null &
    sudo nohup python worker.py recruitment_parse_lagou -e test 1>/dev/null 2>/dev/null &
 done
"""


if __name__ == '__main__':
    s3_url = S3_CODE_BASE_URL.format(app_name=APP_NAME)
    initial_codes = initial_codes.format(
        s3_url=s3_url,
        app_name=APP_NAME,
        process_num=PROCESS_NUM,
    )
    try:
        aws = EC2()
        aws.create_instances(
            instances_name=INSTANCE_NAME, image_id=IMAGE_ID, max_count=INSTANCE_NUM,
            user_data=initial_codes
        )
    except Exception, e:
        logger.error('initial instance error for reason:%s'%str(e))